package com.gensdai.leliang.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.gensdai.leliang.AppApplication;
import com.gensdai.leliang.R;
import com.gensdai.leliang.adapter.Indent_List_Adapter;
import com.gensdai.leliang.base.BaseActivityNoAbs;
import com.gensdai.leliang.common.bean.WechatBean;
import com.gensdai.leliang.dialog.Upload;
import com.gensdai.leliang.dialog.UserSexDialog;
import com.gensdai.leliang.dialog.dialog_select_pay_type_test;
import com.gensdai.leliang.entity.CardCart;
import com.gensdai.leliang.entity.ShopBean;
import com.gensdai.leliang.entity.parseBean.BaseParse;
import com.gensdai.leliang.entity.parseBean.ParentBean;
import com.gensdai.leliang.json_base.json_base;
import com.gensdai.leliang.popupwindow.BasePopupWindow;
import com.gensdai.leliang.remoteInterface.ApiService;
import com.gensdai.leliang.remoteInterface.RetrofitFactory;
import com.gensdai.leliang.retrofitUtils.BaseObserver;
import com.gensdai.leliang.retrofitUtils.ModelFilteredFactory;
import com.gensdai.leliang.utils.BaseUtils;
import com.gensdai.leliang.utils.PreferencesUtils;
import com.gensdai.leliang.view.Toaster;
import com.gensdai.leliang.wxapi.WXPayEntryActivity;
import com.gensdai.leliang.zfb.PayResult;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.trello.rxlifecycle2.android.BuildConfig;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/6/5.
 */

public class Indent extends BaseActivityNoAbs implements View.OnClickListener, dialog_select_pay_type_test.PayTypeClick {

    @BindView(R.id.ui_title)
    TextView uiTitle;
    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.indent_no)
    LinearLayout indentNo;
    @BindView(R.id.indent_list)
    ListView indentList; //数据列表
    @BindView(R.id.all_indent)
    RadioButton allIndent; //全部
    @BindView(R.id.wait_indent)
    RadioButton waitIndent;// 付款
    @BindView(R.id.wait_shipments)
    RadioButton waitShipments;//发货
    @BindView(R.id.wait_delivery)
    RadioButton waitDelivery;//收货
    @BindView(R.id.wait_evaluate)
    RadioButton waitEvaluate;//待评价

    private String indent_state;//订单状态
    private Indent_List_Adapter list_adapter;
    private List<ShopBean> list_data;
    private Upload up;
    UserSexDialog user;
    CardCart cardCart;
    SharedPreferences share;
    SharedPreferences.Editor ed;

    private String oderid = "'";
    private final int ENTER = 1;// 登录标识
    private Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                case ENTER:
                    if (up != null && up.isShowing()) {
                        up.dismiss();
                    }
                    try {
                        if (new json_base().GOOD((String) msg.obj)) {
                            if (list_data.size() > 0) {
                                list_data.clear();
                            }
                            list_data = (List<ShopBean>) new json_base().jsonIndent(new JSONObject((String) msg.obj));
                            SetmList(indent_state);
                        } else {
                            Toast.makeText(
                                    Indent.this,
                                    new JSONObject((String) msg.obj)
                                            .getString("message"),
                                    Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.indent);
        ButterKnife.bind(this);

        //wxpay begin
        msgApi = WXAPIFactory.createWXAPI(this, AppApplication.APPID, false);
        //动态注册，微信支付会调用广播在当前activity的生命周期內运行
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d("BroadcastReceiver", "BroadcastReceiver");
                if (intent.getAction().equals(WXPayEntryActivity.INDENTORDER)) {
                    //Do Something
                    String payResultType = intent.getStringExtra("type");
                    if (!TextUtils.isEmpty(payResultType)) {
                        //付款成功
                        if (TextUtils.equals(WXPayEntryActivity.CODE_SUCCESS, payResultType)) {
                            if (test != null && test.isShowing())
                                test.dismiss();
                            Toast.makeText(Indent.this, "付款成功",
                                    Toast.LENGTH_SHORT).show();
                            //同步回调服务器
//                        returnPayUrl(resultInfo);
                            OrderManageRequestStr(indent_state);
                        } else if (TextUtils.equals(WXPayEntryActivity.CODE_CANCEL, payResultType)) {
                            //取消操作
                        }
                    }
                }
            }
        };
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
        mLocalBroadcastManager.registerReceiver(mReceiver, new IntentFilter(WXPayEntryActivity.INDENTORDER));
        msgApi.registerApp(AppApplication.APPID);
        //wxpayend

        init();
        setonclick();
    }

    private void setonclick() {
        back.setOnClickListener(this);
        allIndent.setOnClickListener(this);
        waitIndent.setOnClickListener(this);
        waitShipments.setOnClickListener(this);
        waitDelivery.setOnClickListener(this);
        waitEvaluate.setOnClickListener(this);

//        indentList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                Intent go_OrderInfo = new Intent(Indent.this, OrderInfoActivity.class);
//                go_OrderInfo.putExtra(OrderInfoActivity.EXTRA_ORDER_ID, list_data.get(position).getIndentId());
//                Log.e("Indent", "Indent:点击itme:" + position);
//                Indent.this.startActivity(go_OrderInfo);
//            }
//        });

    }

    /**
     * 初始化
     */
    private void init() {
        indent_state = getIntent().getStringExtra("state");
        uiTitle.setText(getString(R.string.my_indent));
        share = getSharedPreferences("User", MODE_PRIVATE);
        ed = share.edit();
        up = new Upload(this);
        user = new UserSexDialog(Indent.this, UserSexDialog.WULIU);
        list_data = new ArrayList<ShopBean>();
        switch (Integer.parseInt(indent_state)) {
            case 0:
                indent_state = "0";
                allIndent.setChecked(true);
                break;
            case 1:
                indent_state = "1";
                waitIndent.setChecked(true);
                ed.putString("daifuNum", "0");
                break;
            case 2:
                indent_state = "2";
                waitShipments.setChecked(true);
                ed.putString("daifaNum", "0");
                break;
            case 3:
                indent_state = "3";
                waitDelivery.setChecked(true);
                ed.putString("daishouNum", "0");
                break;
            case 4:
                indent_state = "4";
                waitEvaluate.setChecked(true);
                ed.putString("daishouNum", "0");
                break;
            default:
                break;
        }
        ed.commit();
    }

    private void SetmList(String indent_state) {

        if (list_data.size() > 0) {
            list_adapter = new Indent_List_Adapter(this, list_data, indent_state);
            list_adapter.setOnItemMenuClick(click);
            indentList.setAdapter(list_adapter);
            list_adapter.notifyDataSetChanged();
            indentNo.setVisibility(View.GONE);
            indentList.setVisibility(View.VISIBLE);
        } else {
            indentNo.setVisibility(View.VISIBLE);
            indentList.setVisibility(View.GONE);
        }

    }


    dialog_select_pay_type_test test;
    //订单管理列表按钮点击事件
    Indent_List_Adapter.onItemMenuClick click = new Indent_List_Adapter.onItemMenuClick() {

        @Override
        public void onPayClick(double waitPayPrice, String id) {
            test = new dialog_select_pay_type_test(Indent.this, getSupportFragmentManager());
            test.setPrice((float)waitPayPrice);
            test.setOrderID(id);
            test.setOnPayTypeClick(Indent.this);    //调用付款回调
            test.setOnKeyBordCallBackListener(keybordListener);
            test.showPopupWindow();
            test.setOnDismissListener(new BasePopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {

                }
            });
        }

        @Override
        public void onCancelClick(String orderid) {
            postOrderCancel(orderid);
        }

        @Override
        public void onjinru(int postion) {
            Intent go_OrderInfo = new Intent(Indent.this, OrderInfoActivity.class);
            go_OrderInfo.putExtra(OrderInfoActivity.EXTRA_ORDER_ID, list_data.get(postion).getIndentId());
            Log.e("Indent", "Indent:点击itme:" + postion);
            Log.e("Indent", "Indent:getIndentId:" + list_data.get(postion).getIndentId());
            Indent.this.startActivity(go_OrderInfo);
        }

        @Override
        public void queren(String orderid) {
            user.show();
            oderid = orderid;
//            ConfirmReceipt(orderid);
        }

        @Override
        public void pingjia(int postion) {
            List<BaseParse.OrderAttributeMapBean> list = new ArrayList<BaseParse.OrderAttributeMapBean>();
            BaseParse.OrderAttributeMapBean bean;
            CardCart cardCart;
            for (int i = 0; i < list_data.get(postion).getCardCartsList().size(); i++) {
                bean = new BaseParse.OrderAttributeMapBean();
                cardCart = list_data.get(postion).getCardCartsList().get(i);
                bean.productName = cardCart.getShopname();
                bean.attributeName = cardCart.getProductAttributeName();
                bean.productAttributeId = cardCart.getProductAttributeId();
                bean.orderAttributeId = cardCart.getOrderAttributeId();
                bean.logo = cardCart.getIc_path();
//                bean.stockNum = Integer.parseInt(cardCart.getSurplusNumber());
                bean.buyPrice = cardCart.getVipPrice();
                bean.buyNum = Integer.parseInt(cardCart.getNumber());
                list.add(bean);
            }
            Intent it = new Intent(Indent.this, PostComment.class);
            it.putExtra(PostComment.EXTRA_OBJS, (Serializable) list);
            it.putExtra(PostComment.EXTRA_ID, list_data.get(postion).getIndentId());
            startActivity(it);
        }

        @Override
        public void tuikuan(int postion) {
            Intent it = new Intent(Indent.this, ApplyRefund.class);
            it.putExtra(ApplyRefund.EXTRA_ORDERID, list_data.get(postion).getIndentId());
            startActivity(it);

        }

        @Override
        public void applybtn(int postion) {
            Intent it = new Intent(Indent.this, ActivityApplyResultInfo.class);
            it.putExtra(ActivityApplyResultInfo.EXTRA_ORDERID, list_data.get(postion).getIndentId());
            startActivity(it);
        }

    };

    @Override
    protected void onStart() {
        super.onStart();
        OrderManageRequestStr(indent_state);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                this.finish();
                break;
            case R.id.all_indent:
                indent_state = "0";
                ed.commit();
                OrderManageRequestStr(indent_state);
                break;
            case R.id.wait_indent:
                indent_state = "1";
                ed.putString("daifuNum", "0");
                ed.commit();
                OrderManageRequestStr(indent_state);
                break;
            case R.id.wait_shipments:
                indent_state = "2";
                ed.putString("daifaNum", "0");
                ed.commit();
                OrderManageRequestStr(indent_state);
                break;
            case R.id.wait_delivery:
                indent_state = "3";
                ed.putString("daishouNum", "0");
                ed.commit();
                OrderManageRequestStr(indent_state);
                break;
            case R.id.wait_evaluate:
                indent_state = "4";
                ed.putString("waitComment", "0");
                ed.commit();
                OrderManageRequestStr(indent_state);
                break;
            case R.id.j:
                user.dismiss();
                ConfirmReceipt(oderid);
                break;
            case R.id.q:
                user.dismiss();
                break;
            default:
                break;
        }

    }

    /**
     * 调用订单
     */
    private void OrderManageRequestStr(String flag) {
        //获取edit的值后请求

        Map<String, String> loginParams = new HashMap<>();
        if (flag.equals("4")) {
            loginParams.put("hasEvaluate", "false");   //标识
        }
        loginParams.put("flag", flag);   //标识
        loginParams.put("userId", share.getString("user_id", ""));
        loginParams.put("page", "1");
//        loginParams.put("token", getSharedPreferences("User", MODE_PRIVATE).getString("token", ""));
        toStr(loginParams);
    }

    //返回字符串类型
    private void toStr(Map<String, String> loginParams) {
        up.show();
        ApiService.getInstance(this).OrderManageRequestStr(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        Log.e("quick_login", s);
                        Message msg = new Message();
                        msg.what = ENTER;
                        msg.obj = s;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        up.dismiss();
//                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }


    dialog_select_pay_type_test.KeybordListener keybordListener = new dialog_select_pay_type_test.KeybordListener() {


        @Override
        public void onInputCompleted(CharSequence password) {


        }

        @Override
        public void onInputCompleted(CharSequence password, String ordereid) {
            //执行验余额支付的接口会返回错误字符
            postBanlancePay(password.toString(), ordereid);
        }

        @Override
        public void onForgetPassword() {

        }

        @Override
        public void onPasswordCorrectly() {
            test.dismiss();
            OrderManageRequestStr(indent_state);
        }

        @Override
        public void onCancel() {
        }

    };


    private void postBanlancePay(String pay, String orderid) {
        String userid = PreferencesUtils.getStringPreference(this, OrderPreperActivity.prefreceName, OrderPreperActivity.prefrece_userid, ""); //获取用户id没有登陆就是没有

        Map<String, String> params = new HashMap<>();
        params.put("userId", userid);   //手机号
        params.put("orderId", orderid);
        params.put("payPassword", BaseUtils.EncryptedPassword(pay));
        params.put("token", getSharedPreferences("User", MODE_PRIVATE).getString("token", ""));

        ApiService.getInstance(this).payBalance(params)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<ParentBean>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ParentBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();
                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull ParentBean s) {
                        //处理得到的数据
                        Toast.makeText(Indent.this, s.getMessage(), Toast.LENGTH_SHORT).show();

                        if (s.isSuccess()) {
                            test.setkeyPadStatus(true);
                        } else {
                            test.setkeyPadStatus(false, s.getMessage());
                        }
                        Log.e("quick_login", s.getMessage());


                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        e.printStackTrace();
                        test.setkeyPadStatus(false, "出现了一个问题");
//                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }

    /**
     * 取消订单
     *
     * @param orderid
     */
    private void postOrderCancel(final String orderid) {
        Map<String, String> params = new HashMap<>();
        params.put("orderId", orderid);
        params.put("token", getSharedPreferences("User", MODE_PRIVATE).getString("token", ""));
        ApiService.getInstance(this).postOrderCancel(params)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<BaseParse>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }
                        if (up != null) {
                            up.show();
                        }
                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseParse>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();
                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull BaseParse s) {
                        //处理得到的数据
                        Toast.makeText(Indent.this, s.message, Toast.LENGTH_SHORT).show();
                        OrderManageRequestStr(indent_state);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        e.printStackTrace();
//                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");

                        if (up != null && up.isShowing()) {
                            up.dismiss();
                        }
                    }
                });

    }

    /**
     * 确认收货
     *
     * @param orderid
     */
    private void ConfirmReceipt(final String orderid) {
        Map<String, String> params = new HashMap<>();
        params.put("orderId", orderid);
        params.put("tokenId", getSharedPreferences("User", MODE_PRIVATE).getString("token", ""));
        params.put("userId", getSharedPreferences("User", MODE_PRIVATE).getString("user_id", ""));
        ApiService.getInstance(this).ConfirmReceipt(params)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }
                        if (up != null) {
                            up.show();
                        }
                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();
                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@io.reactivex.annotations.NonNull String s) {
                        OrderManageRequestStr(indent_state);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        e.printStackTrace();
//                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");

                        if (up != null && up.isShowing()) {
                            up.dismiss();
                        }
                    }
                });

    }


    /*获取Alipay的支付 URL*/
    @Override
    public void PayAli(String orderID) {
        String userid = PreferencesUtils.getStringPreference(AppApplication.getContext(), OrderPreperActivity.prefreceName, OrderPreperActivity.prefrece_userid, ""); //
        String userno = PreferencesUtils.getStringPreference(AppApplication.getContext(), OrderPreperActivity.prefreceName, OrderPreperActivity.prefrece_userno, ""); //

        Map<String, String> params = new HashMap<>();
        params.put("userno", userno);
        params.put("userId", userid);
        params.put("orderId", orderID);
        params.put("token", getSharedPreferences("User", MODE_PRIVATE).getString("token", ""));

        ModelFilteredFactory.compose(RetrofitFactory.getInstance().API().createAliPay(params))
                .compose(this.<BaseParse<BaseParse.properOrder>>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }
                        if (up != null) {
                            up.show();
                        }
                        Log.d("accept", "accept");
                    }
                })
                .subscribe(
                        new Observer<BaseParse<BaseParse.properOrder>>() {
                            @Override
                            public void onSubscribe(@NonNull Disposable d) {
                                //可以取消订阅
                                //还可以判断是否处于取消状态
                                //boolean b=d.isDisposed();

                                Log.d("onSubscribe", "onSubscribe");
                            }

                            @Override
                            public void onNext(@NonNull BaseParse<BaseParse.properOrder> s) {
                                //处理得到的数据
                                if (BuildConfig.DEBUG) {
                                    Toast.makeText(Indent.this, s.message, Toast.LENGTH_SHORT).show();
                                }
                                if (s.data != null && s.data.payAliUrl != null) {
                                    startPayAli(s.data.payAliUrl);
                                } else {
                                    if (BuildConfig.DEBUG) {
                                        Toaster.showOneToast("订单管理获取服务器aliUrl失败，该窗口只会在开发模式中显示");
                                    }
                                }
                                Log.e("quick_login", s.message);

                                if (up != null) {
                                    up.dismiss();
                                }
                            }

                            @Override
                            public void onError(@NonNull Throwable e) {
                                //异常处理
                                e.printStackTrace();
                                if (up != null) {
                                    up.dismiss();
                                }
                            }

                            @Override
                            public void onComplete() {
                                //监听完毕后的处理
                                Log.d("onComplete", "onComplete");
                                if (up != null) {
                                    up.dismiss();
                                }
                            }
                        }
                );
    }

    public static IWXAPI msgApi;

    //检查微信是否安装
    public boolean isWXAppInstalled() {
        return msgApi.isWXAppInstalled();
    }

    @Override
    public void PayWechat(final String orderID) {

        if (!isWXAppInstalled()) {
            Toaster.showOneToast("没有检测到安装微信客户端，请更换支付方式");
            return;
        }


        String userid = PreferencesUtils.getStringPreference(AppApplication.getContext(), OrderPreper3Activity.prefreceName, OrderPreper3Activity.prefrece_userid, ""); //
        String userno = PreferencesUtils.getStringPreference(AppApplication.getContext(), OrderPreper3Activity.prefreceName, OrderPreper3Activity.prefrece_userno, ""); //

        Map<String, String> params = new HashMap<>();
        params.put("userno", userno);
        params.put("userId", userid);
        params.put("orderId", orderID);
        params.put("clientType", AppApplication.ClientType);

        ModelFilteredFactory.compose(RetrofitFactory.getInstance().API().CreateWechatPay(params))
                .compose(this.<BaseParse<WechatBean>>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }
                        if (up != null) {
                            up.show();
                        }
                        Log.d("accept", "accept");
                    }
                })
                .subscribe(new BaseObserver<WechatBean>(Indent.this) {
                               @Override
                               public void onHandleSuccess(WechatBean properOrder) {
                                   //处理得到的数据

                                   if (properOrder != null) {
                                       //变换为wechat的对象开始调用微信支付
                                       PayReq request = new PayReq();

                                       request.appId = properOrder.appid;

                                       request.partnerId = properOrder.partnerid;

                                       request.prepayId = properOrder.prepayid;

                                       request.packageValue = properOrder.packages;

                                       request.nonceStr = properOrder.noncestr;

                                       request.timeStamp = properOrder.timestamp;

                                       request.sign = properOrder.sign;
                                       request.extData = WXPayEntryActivity.INDENTORDER + "#" + orderID;

                                       msgApi.sendReq(request);
                                   } else {
                                       if (BuildConfig.DEBUG) {
                                           Toaster.showOneToast("获取服务器wechatUrl失败，该窗口只会在开发模式中显示");
                                       }
                                   }

                                   if (up != null) {
                                       up.dismiss();
                                   }
                               }

                               @Override
                               public void onHandleError(int code, String message) {
                                   if (BuildConfig.DEBUG) {
                                       Toast.makeText(Indent.this, message, Toast.LENGTH_SHORT).show();
                                   }
                               }

                               @Override
                               public void onRequestEnd() {
                                   super.onRequestEnd();
                                   if (up != null) {
                                       up.dismiss();
                                   }
                               }

                               @Override
                               public void onFailure(Throwable e) {
                                   super.onFailure(e);
                                   if (up != null) {
                                       up.dismiss();
                                   }
                               }
                           }
                );
    }

    private void startPayAli(final String url) {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(Indent.this);
                Map<String, String> result = alipay.payV2(url, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private static final int SDK_PAY_FLAG = 1;

    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult(
                            (Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    Log.e("my_wallet", "resultInfo:" + resultInfo);
                    Log.e("my_wallet", "resultStatus:" + resultStatus);
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(Indent.this, "付款成功",
                                Toast.LENGTH_SHORT).show();
                        //同步回调服务器
                        if (test != null && test.isShowing())
                            test.dismiss();
//                        returnPayUrl(resultInfo);
                        OrderManageRequestStr(indent_state);

                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(Indent.this, "付款失败",
                                Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                default:
                    up.dismiss();
                    break;
            }
        }

        ;
    };


    LocalBroadcastManager mLocalBroadcastManager;
    BroadcastReceiver mReceiver;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocalBroadcastManager.unregisterReceiver(mReceiver);
    }

}
